#!/usr/bin/env Rscript

## Install all required packages for the project

required_packages <- c(
    # data processing / modeling helpers
    "car",
    "nnet",
    "mgcv",
    "here",
    "dplyr",
    "janitor",
    "tidyr",
    "ggplot2",
    "purrr",
    "stringr",
    "scales",
    "glue",
    "forcats",
    "tidyverse",
    "rlang",
    "broom",
    
    # tables and assessing models
    "stargazer",
    "kableExtra",
    "xtable",
    "margins",
    
    # importing
    "readxl",
    "haven",
    
    # text analysis
    "tidytext",
    "topicmodels",
    "tm",
    "SnowballC",
    "sentimentr",
    
    # data visualization
    "ggtext",
    "sjPlot",
    "gridExtra",
    "ggridges",
    "ggmosaic",
    "jtools",
    "interactions",
    "cowplot",
    "amerika",
    "patchwork",
    "gridtext",
    
    # matching
    "cobalt",
    "CBPS",
    "MatchIt",
    
    # modeling
    "pscl",
    "boot",
    "MASS",
    "DescTools",
    "mediation",
    "marginaleffects",
    "ggeffects",
    "effectsize",
    
    # correlations, PCA, RF
    "corrr",
    "GGally",
    "corrplot",
    "randomForest",
    "FactoMineR",
    "factoextra",
    
    # missing data
    "naniar",
    "Amelia",
    "mice",
    
    # misc
    "vtable",
    "sjlabelled",
    "conflicted",
    "rstudioapi",
    "knitr"
)

## Ensure a CRAN repo is set 
r <- getOption("repos")
if (is.null(r) || identical(unname(r["CRAN"]), "@CRAN@")) {
    options(repos = c(CRAN = "https://cloud.r-project.org"))
}

installed  <- rownames(installed.packages())
to_install <- setdiff(required_packages, installed)

if (length(to_install) > 0L) {
    message("Installing packages: ", paste(to_install, collapse = ", "))
    install.packages(to_install)
} else {
    message("All required packages are already installed.")
}

